<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card>
                    <div slot="header" class="clearfix">
                        <h3>第一步：填写档案基本信息</h3>
                    </div>
                    <el-form ref="archiveRef" :model="form" :rules="rules" label-position="top" label-width="85px">
                        <el-form-item label="档案名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入档案名称" style="width: 100%;" />
                        </el-form-item>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="起始时间(档案内文件的最早时间)" prop="startDate" width="100%">
                                <el-date-picker clearable v-model="form.startDate" type="date" value-format="YYYY-MM-DD"
                                    placeholder="请选择起始时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="终止时间(档案内文件的最晚时间)" prop="endDate" width="100%">
                                <el-date-picker clearable v-model="form.endDate" type="date" value-format="YYYY-MM-DD"
                                    placeholder="请选择终止时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="归档时间(收藏于档案馆的时间)" prop="guidangTime">
                                <el-date-picker clearable v-model="form.guidangTime" type="date"
                                    value-format="YYYY-MM-DD" placeholder="请选择归档时间">
                                </el-date-picker>
                            </el-form-item>
                        </div>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="档案门类" prop="category" width="100%">
                                <el-select v-model="form.category" placeholder="请选择所属类别">
                                    <el-option v-for="category in categoryList" :key="category.id"
                                        :label="category.name" :value="category.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="载体类型" prop="carrierType" width="100%">
                                <el-select v-model="form.carrierType" placeholder="请选择载体类型">
                                    <el-option v-for="dict in iams_carrier_type" :key="dict.value" :label="dict.label"
                                        :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="保管期限" prop="retentionPeriod" width="100%">
                                <el-select v-model="form.retentionPeriod" placeholder="请选择保管期限">
                                    <el-option v-for="dict in iams_retention_period" :key="dict.value"
                                        :label="dict.label" :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="保密级别" prop="secretLevel" width="100%">
                                <el-select v-model="form.secretLevel" placeholder="请选择保密级别">
                                    <el-option v-for="dict in iams_secret_level" :key="dict.value" :label="dict.label"
                                        :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="保密期限" prop="secretPeroid">
                                <el-select v-model="form.secretPeroid" placeholder="请选择保密期限" width="100%">
                                    <el-option v-for="dict in iams_secret_period" :key="dict.value" :label="dict.label"
                                        :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="解密日期" prop="desecretDate" width="100%">
                                <el-date-picker clearable v-model="form.desecretDate" type="date"
                                    value-format="YYYY-MM-DD" placeholder="请选择解密日期">
                                </el-date-picker>
                            </el-form-item>
                        </div>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="所属全宗" prop="fonds" width="100%">
                                <el-select v-model="form.fonds" placeholder="请选择所属全宗">
                                    <el-option v-for="fonds in fondsList" :key="fonds.id" :label="fonds.name"
                                        :value="fonds.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="形成单位" prop="formationUnit" style="width: 50%;">
                                <el-input v-model="form.formationUnit" placeholder="请输入形成单位" />
                            </el-form-item>
                            <el-form-item label="移交单位" prop="transferUnit" style="width: 50%;">
                                <el-input v-model="form.transferUnit" placeholder="请输入移交单位" />
                            </el-form-item>
                        </div>
                        <el-form-item label="档案目录" prop="directory">
                            <el-input v-model="form.directory" type="textarea" placeholder="请在右侧目录模板中选择档案目录结构" />
                        </el-form-item>
                        <el-form-item label="档案简介" prop="description">
                            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="电子档案位置" prop="dianziLocation" style="width: 50%;">
                                <el-input v-model="form.dianziLocation"
                                    placeholder="请输入电子档案存储位置，如 C:\ProgramData\Alibaba\AlibabaProtectDT" />
                            </el-form-item>
                            <el-form-item label="实体档案位置" prop="shitiLocation" style="width: 50%;">
                                <el-input v-model="form.shitiLocation" placeholder="请输入实体档案存放位置，如 2号库2排3列柜第3节第4层" />
                            </el-form-item>
                        </div>
                        <el-form-item label="档案编号" prop="danghao">
                            <el-input v-model="form.danghao" placeholder="请输入档号(可以根据上面的基本信息按指定规则生成)" width="100%">
                                <template #append>
                                    <el-button type="primary">点击生成</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="射频标签号" prop="rfid">
                            <el-input v-model="form.rfid" placeholder="请输入射频标签号(可以根据档案编号按指定规则生成)" width="100%">
                                <template #append>
                                    <el-button type="primary">自动生成</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                        <el-form-item label="额外信息" prop="extraInfo">
                            <el-button type="primary" @click="showDialog">添加</el-button>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <el-button @click="cancel">取 消</el-button>
                        <el-button type="primary" @click="submitForm">提 交</el-button>
                    </template>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card class="box-card">
                    <template #header>
                        <div class="clearfix">
                            <h3>第二步：选择档案目录</h3>
                        </div>
                    </template>
                    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
                        <el-form-item label="目录名称" prop="name">
                            <el-input v-model="queryParams.name" placeholder="请输入目录名称" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                    <el-table v-loading="loading" :data="directoryList">
                        <el-table-column label="主键" align="center" prop="id" />
                        <el-table-column label="目录名称" align="center" prop="name" />
                        <el-table-column label="目录结构" align="center" prop="structure">
                            <template #default="scope">
                                <el-button link type="primary" @click="viewTreeDirectory(scope.row)"
                                    v-hasPermi="['manage:directory:query']">查看目录结构</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template #default="scope">
                                <el-button link type="primary" @click="selectArchiveDirectory(scope.row)">选择</el-button>
                                <el-button link type="primary" @click="handleDetail(scope.row)"
                                    v-hasPermi="['manage:directory:query']">查看</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                        v-model:limit="queryParams.pageSize" @pagination="getDirectoryList" />
                </el-card>
            </el-col>
        </el-row>
        <el-dialog title="目录结构" v-model="open" width="50%">
            <el-tree :data="directory" :default-expand-all="true" :expand-on-click-node="true" />
            <template #footer>
                <el-button @click="closeDirectoryDialog">关 闭</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogFormVisible" title="档案额外信息" width="550">
            <el-form :model="extraInfo">
                <!-- 动态生成每个 div -->
                <div v-for="(info, index) in extraInfoList" :key="index"
                    style="display: flex; align-items: center; margin-bottom: 16px;">
                    <el-form-item label="属性" style="margin-right: 16px; margin-bottom: 0;">
                        <el-input v-model="info.label" autocomplete="off" style="width: 180px;" />
                    </el-form-item>
                    <el-form-item label="内容" style="margin-right: 16px; margin-bottom: 0;">
                        <el-input v-model="info.value" autocomplete="off" style="width: 180px;" />
                    </el-form-item>
                    <!-- 减号按钮 -->
                    <el-button v-if="extraInfoList.length > 1" type="danger" @click="removeExtraInfo(index)"
                        :icon="Minus" circle style="margin-left: 8px;"></el-button>
                </div>
                <!-- 加号按钮 -->
                <div style="display: flex; justify-content: center; margin-top: 16px;">
                    <el-button type="primary" @click="addExtraInfo" :icon="Plus" circle></el-button>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer" style="text-align: right;">
                    <el-button @click="cancelDialog">取消</el-button>
                    <el-button type="primary" @click="saveExtraInfoList">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="add">
import { Plus, Minus } from '@element-plus/icons-vue';
import { ref, reactive, onMounted } from 'vue'
import { addArchive } from '@/api/manage/archive'
import { listDirectory } from "@/api/manage/directory";
import { listCategory } from "@/api/manage/category";
import { listFonds } from "@/api/manage/fonds";

const { proxy } = getCurrentInstance()
const { iams_carrier_type, iams_retention_period, iams_secret_period, iams_secret_level } = proxy.useDict('iams_carrier_type', 'iams_retention_period', 'iams_secret_period', 'iams_secret_level');

const data = reactive({
    form: {
        danghao: null,
        name: null,
        secretLevel: null,
        secretPeroid: null,
        desecretDate: null,
        retentionPeriod: null,
        carrierType: null,
        startDate: null,
        endDate: null,
        guidangTime: null,
        shitiLocation: null,
        dianziLocation: null,
        description: null,
        formationUnit: null,
        transferUnit: null,
        documentCount: null,
        directory: null,
        extraInfo: null,
    },
    rules: {
        name: [
            { required: true, message: "档案名称不能为空", trigger: "blur" }
        ],
        directory: [
            { required: true, message: "档案目录不能为空", trigger: "blur" }
        ],
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
    },
});
const { form, rules, queryParams } = toRefs(data);

const directoryList = ref([]);
const loading = ref(true);
const total = ref(0);
const open = ref(false);
const directory = ref(null);


const extraInfoList = ref([{ label: '', value: '' }]);
const dialogFormVisible = ref(false)
const extraInfo = reactive({
    label: '',
    value: '',
})
function showDialog() {
    dialogFormVisible.value = true
}
function cancelDialog() {
    dialogFormVisible.value = false
    extraInfoList.value = [{ label: '', value: '' }];
}
function addExtraInfo() {
    extraInfoList.value.push({ label: '', value: '' });
}

function saveExtraInfoList() {
    if (extraInfoList.value.length === 0) {
        proxy.$message({
            message: '请至少添加一个额外信息',
            type: 'warning'
        });
        return;
    }
    form.value.extraInfo = JSON.stringify(extraInfoList.value);
    proxy.$modal.msgSuccess("额外信息保存成功");
    dialogFormVisible.value = false;
}

function removeExtraInfo(index) {
    extraInfoList.value.splice(index, 1);
}

/** 查询目录列表 */
function getDirectoryList() {
    loading.value = true;
    listDirectory(queryParams.value).then(response => {
        directoryList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}
/** 查看目录详情按钮操作 */
function handleDetail(row) {
    proxy.$router.push({ path: "/manage/directory/drt-detail", query: { id: row.id } });
}
/** 搜索目录按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getDirectoryList();
}

/** 重置目录查询按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}
getDirectoryList();

// 查询分类列表
const categoryList = ref([]);
/** 查询档案门类管理列表 */
function getCategoryList() {
    listCategory({}).then(response => {
        categoryList.value = response.rows;
    });
    console.log(categoryList.value);
}
getCategoryList();
// 全宗列表
const fondsList = ref([]);
/** 查询全宗列表 */
function getFondsList() {
    listFonds({}).then(response => {
        fondsList.value = response.rows;
    });
}
getFondsList();

/** 为档案选择目录 */
function selectArchiveDirectory(row) {
    form.value.directory = row.structure;
}
/** 查看目录结构 */
function viewTreeDirectory(row) {
    directory.value = JSON.parse(row.structure);
    open.value = true;
}

/** 关闭目录结构弹窗 */
function closeDirectoryDialog() {
    open.value = false;
    directory.value = null;
}
// 取消按钮
function cancel() {
    reset();
}

// 表单重置
function reset() {
    form.value = {
        danghao: null,
        name: null,
        secretLevel: null,
        secretPeroid: null,
        desecretDate: null,
        retentionPeriod: null,
        carrierType: null,
        startDate: null,
        endDate: null,
        guidangTime: null,
        shitiLocation: null,
        dianziLocation: null,
        description: null,
        formationUnit: null,
        transferUnit: null,
        documentCount: null,
        directory: null,
    };
    proxy.resetForm("archiveRef");
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["archiveRef"].validate(valid => {
        if (valid) {
            addArchive(form.value).then(response => {
                proxy.$modal.msgSuccess("新增成功");
                proxy.$router.push({ path: "/manage/archive/arc-list" });
            });
        }
    });
}

</script>

<style scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    padding-right: 12px;
}
</style>